import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/widget/common/empty_tips.dart';
import 'package:material_collection_app/widget/manage/mange_card.dart';
import 'package:material_collection_app/widget/common/refresh.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import '../utils/utils.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HistoryPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<HistoryPage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  List list = [];
  int currentPage = 1;
  int lastPage = 1;
  bool loadSuccess = false;
  String keywords;
  TextEditingController _idController = new TextEditingController();
  TextEditingController _nameController = new TextEditingController();
  TextEditingController _usernameController = new TextEditingController();

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  // 加载数据
  _loadData({bool loadMore = false}) async {
    loadSuccess = false;

    String materialName = _idController.text.trim();

    if (loadMore) {
      currentPage++;
    } else {
      currentPage = 1;
    }

    Map params = {
      'page': currentPage,
      'key': materialName,
    };

    DioUtils.request("goods/lists",
        context: context, method: "POST", params: params, onSuccess: (res) {
      if (res['code'] == 1) {
        if (mounted) {
          setState(() {
            if (loadMore) {
              list.addAll(res["data"]["data"]);
            } else {
              list = res["data"]["data"];
            }

            currentPage = res['data']['current_page'];
            lastPage = res['data']['last_page'];
            loadSuccess = true;
          });
        }
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 下拉刷新
  _onRefresh() async {
    _refreshController.loadComplete();
    _loadData();

    await Future.delayed(Duration(milliseconds: 600));
    _refreshController.refreshCompleted();
  }

  // 加载更多
  _onLoading() async {
    await Future.delayed(Duration(milliseconds: 200));

    if (currentPage == lastPage) {
      _refreshController.loadNoData();
      return;
    }

    // 加载更多数据
    if (currentPage < lastPage) {
      _loadData(loadMore: true);
      _refreshController.loadComplete();
    }
  }

  Widget _buildPage() {
    // // 无数据
    if (loadSuccess && list.length == 0) {
      return EmptyTips(
        refreshController: _refreshController,
        onRefresh: _onRefresh,
        backgroundColor: Utils.hexToColor('#F7F6F9'),
      );
    }

    return ListView.builder(
        itemCount: list.length,
        padding: EdgeInsets.only(bottom: 60.w),
        itemBuilder: (BuildContext context, int index) {
          return ManageCard(item: list[index]);
        });
  }

  Widget _buildInput(
      String title, TextEditingController controller, String hintText) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            title,
            style:
                TextStyle(color: Utils.hexToColor('#999999'), fontSize: 28.w),
          ),
          Container(
            width: 555.w,
            height: 56.h,
            // margin: EdgeInsets.only(top: 30.w),
            child: TextField(
              controller: controller,
              style: TextStyle(fontSize: 28.w, color: Colors.black), //输入文本的样式
              decoration: InputDecoration(
                hintText: hintText,
                hintStyle: TextStyle(color: Color(0xFFC8C8D9), fontSize: 28.w),
                contentPadding: EdgeInsets.fromLTRB(21.w, 0, 21.w, 0),
                fillColor: Colors.white,
                filled: true,
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(4.w),
                  ),
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(4.w),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSearchButton() {
    return Align(
      alignment: Alignment.centerRight,
      child: Container(
        width: 555.w,
        child: Align(
            alignment: Alignment.centerLeft,
            child: Container(
              width: 120.w,
              height: 50.h,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Utils.hexToColor('#297CFF'),
                  padding: EdgeInsets.all(0),
                ),
                onPressed: () {
                  _loadData();
                },
                child: Text(
                  '搜索',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            )),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
      appBar: TopBar(
        title: '历史记录',
        backgroundColor: Utils.hexToColor('#297CFF'),
      ),
      body: Container(
          color: Utils.hexToColor('#F5F6FA'),
          child: Column(children: <Widget>[
            Container(
              height: 200.h,
              color: Colors.white,
              padding: EdgeInsets.fromLTRB(25.w, 30.h, 25.w, 36.h),
              child: Column(
                children: <Widget>[
                  _buildInput('搜索条件', _idController, '编号、物资名称'),
                  // _buildInput('物资名称：', _nameController, '请填写物资名称'),
                  // _buildInput('经办人员：', _usernameController, '请填写经办人员（选填）'),
                  _buildSearchButton()
                ],
              ),
            ),
            Expanded(
                child: Container(
                    padding: EdgeInsets.fromLTRB(25.w, 23.w, 25.w, 0),
                    child: Refresh(
                        refreshController: _refreshController,
                        onRefresh: _onRefresh,
                        onLoading: _onLoading,
                        headBottom: 10,
                        child: _buildPage())))
          ])),
    );
  }
}
